/*
	SaveClip By DreamVB
	Version 1.0
	A small tool tosaave clipboard text to a file or write to STDOUT

	Please feel free to to use as you like.
	Please let me know if you found this code usfull e. dreamvb@outlook.com
*/

#include <iostream>
#include <stdio.h>
#include <Windows.h>

using namespace std;
using std::cout;
using std::endl;

void DisplayErrror(char *msg){
	cout << msg << endl;
}

int main(int argc, char* argv[]){
	char * lzBuffer = NULL;
	FILE *fout = NULL;
	HANDLE hClip;

	if(argc <=1){
		//The data will be writen to the concole.
		fout = stdout;
	}else{

		//Check for help flag
		if(argv[1][0]=='/'){
			if(argv[1][1] != '?'){
				DisplayErrror("Invaild flag.");
			}
			else{
				//Display help
				cout << "Usage: " << argv[0] << " [Outputfile]" << endl;
			}
			return 0;
		}else
		{
			//Data will be writen to filename.
			fout = fopen(argv[1],"w");
			if(!fout){
				DisplayErrror("IO/Error cannot write to output file.");
				return 0;
			}
		}
	}

	//Try and open the clipboard.
	if(!OpenClipboard(NULL)){
		DisplayErrror("Cannot open clipboard.");
		return 0;
	}

	//Try and open clipboard data for Text Format
	hClip = GetClipboardData(CF_TEXT);
	
	//Check for NULL
	if(hClip == NULL){
		DisplayErrror("Cannot open clipboard data.");
		return 0;
	}

	//Fetch clipbpard contents into lzBuffer
	lzBuffer = static_cast<char*>( GlobalLock(hClip) );

	//Check we have data.
	if(lzBuffer != NULL){
		//Write to fout
		fprintf(fout,lzBuffer);
	}

	//Tidy up time.
	GlobalUnlock(hClip);
	CloseClipboard();
	//Close file
	fclose(fout);
	return 1;
}